<!--
 * @Author: 汪军 624473119@qq.com
 * @Date: 2023-10-10 18:15:53
 * @LastEditors: 汪军 624473119@qq.com
 * @LastEditTime: 2023-12-12 09:19:50
 * @FilePath: \ekee-web\src\views\end\easy-link\EasyLink.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template lang="pug">
.easy-quota.relative.h100
  div.container.overflow-y
    EnterpriseCenterTitle(:titleList="titleList")
    //- 无先易额度
    .no-quota.flex.justify-center.align-center(v-if="isGuarantee")
      span 您还没有先易额度，请点击提交
      span.refund(@click="onGuaranteeApply") 担保申请
    //- 担保待审核
    .reject(v-else-if="guaranteeInfo.review_status == 1") 
      |
      .tip-loading.f3 您提交的担保请求，担保公司在受理中，请耐心等待。
      .mt2.f4 审核状态：待审核
      .mt2.f4 提交时间：{{ guaranteeInfo.submit_time }}
    //- 担保审核通过
    .no-contract(v-else-if="guaranteeInfo.review_status == 2")
      //- 合同审核状态
      div(v-if="guaranteeInfo.sign_status == 1")
        .content
          .title 您已签订合同，请等待合同全部签署完成，为您发放先易额度。
          .tabs.relative.flex.column.align-baseline
            .flex
              img.img(:src="order2", v-if="tabs[0].active")
              img.img(:src="order3", v-else)
              img.img(:src="order2", v-if="tabs[1].active")
              img.img(:src="order3", v-else)
              img.img(:src="order2", v-if="tabs[2].active")
              img.img(:src="order5", v-else)
            .flex.absolute
              .item.tc(
                v-for="(item, index) in tabs",
                :key="index",
                :class="{ active: item.active }"
              ) {{ item.name }}
            .flex
              .time.tc(v-for="(item, index) in tabs", :key="index") {{ item.time }}
      div(v-if="guaranteeInfo.sign_status == 2")
        .mt4.px4
          el-form(ref="formRef", :model="form", :size="formSize", status-icon)
            el-row(:gutter="40")
              el-col(:span="6")
                el-form-item(label="履约ID", prop="id")
                  el-input(v-model="form.id", placeholder="请输入", clearable)
              el-col(:span="6")
                el-form-item(label="关联订单", prop="order_no")
                  el-input(v-model="form.order_no", placeholder="请输入", clearable)
              el-col(:span="6")
                el-form-item(label="预计还款时间", prop="start_expected_repay_time")
                  el-date-picker(
                    v-model="form.start_expected_repay_time",
                    type="date",
                    format="YYYY-MM-DD",
                    value-format="YYYY-MM-DD",
                    placeholder="选择时间",
                    @change="expectedChangeTime",
                    :size="size"
                  )
              el-col(:span="6")
                el-form-item(label="实际还款时间", prop="start_repay_time")
                  el-date-picker(
                    v-model="form.start_repay_time",
                    type="date",
                    format="YYYY-MM-DD",
                    value-format="YYYY-MM-DD",
                    placeholder="选择时间",
                    @change="repayChangeTime",
                    :size="size"
                  )
              el-col(:span="6")
                el-form-item(label="状态", prop="status")
                  el-select(
                    v-model="form.status",
                    placeholder="请选择",
                    clearable,
                    @change="typeChange"
                  )
                    el-option(
                      v-for="item in statusType",
                      :key="item.id",
                      :label="item.type",
                      :value="item.id"
                    )
              el-col(:span="6")
                el-form-item(label="创建时间", prop="start_create_time")
                  el-date-picker(
                    v-model="form.start_create_time",
                    type="date",
                    format="YYYY-MM-DD",
                    value-format="YYYY-MM-DD",
                    placeholder="选择时间",
                    @change="createChangeTime",
                    :size="size"
                  )
              el-col(:span="6")
              el-col(:span="6")
                .flex.justify-end
                  el-button(type="primary", @click="onQueryChange") 查询
                  el-button(@click="onQueryReset(formRef)") 重置
        .table.px4
          el-table(
            :data="tableData",
            :header-cell-style="tableHeaderStyle",
            :cell-style="tableCellStyle",
            empty-text="暂无数据",
            border,
            style="width: 100%"
          )
            el-table-column(prop="id", label="履约ID", width="74")
            el-table-column(prop="order_no", label="关联订单", width="125")
            el-table-column(prop="money", label="借款额度(元)", width="112")
            el-table-column(prop="start_time", label="开始时间", width="117")
            el-table-column(prop="end_time", label="到期时间", width="117")
            el-table-column(prop="status", label="状态", width="74")
              template(v-slot="scope")
                div(:class="initStatusColor(scope.row.status)") {{ initStatusText(scope.row.status) }}
            el-table-column(prop="is_repaid", label="是否还款", width="88")
              template(v-slot="scope")
                div {{ scope.row.is_repaid == 2 ? "已还款" : "未还款" }}
            el-table-column(prop="payer", label="还款人", width="88")
              template(v-slot="scope")
                div {{ scope.row.payer ? scope.row.payer : "" }}
            el-table-column(prop="repay_time", label="还款时间", width="117")
              template(v-slot="scope")
                div {{ scope.row.repay_time ? scope.row.repay_time : "--" }}
            el-table-column(prop="createtime", label="创建时间", width="117")
            el-table-column(fixed="right", label="操作", width="150")
              template(v-slot="scope", #default)
                el-button(
                  link,
                  type="primary",
                  size="small",
                  @click="onLook(scope.row)"
                ) 查看订单
                el-button(
                  v-if="scope.row.can_repay == 1",
                  link,
                  type="primary",
                  size="small",
                  @click="onRefund(scope.row)"
                ) 去还款
                el-button(
                  v-if="scope.row.can_redeem == 1",
                  link,
                  type="primary",
                  size="small",
                  @click="onRansom(scope.row)"
                ) 赎回钱
      div(v-else)
        .title 您有一份合同待签订
        .content
          .quota.f3 您的担保请求已通过，可担保金额为 {{ guaranteeInfo.estimate_money }}元
          .status.f4 
            |
            .mb2 审核状态：通过
            .mb2 提交时间：{{ guaranteeInfo.submit_time }}
            div 审核时间：{{ guaranteeInfo.review_time }}
          .input-quota.flex
            span.f4 您可修改担保金额为：
            el-input.w-input(
              v-model="guaranteeMoney",
              placeholder="请输入",
              clearable
            )
            span.ml1.f4 元
          .tip.f4 不能超过担保公司提供的担保金
        .btn.flex.justify-center
          el-button(type="primary", @click="onSignContract") 签署合同
    //- 担保审核驳回
    .reject(v-else-if="guaranteeInfo.review_status == 3") 
      |
      .tip-text.f4 审核状态：驳回
      .tip-error.mt2.f4 提交时间：{{ guaranteeInfo.submit_time }}
      .tip-error.mt2.f4 审核时间：{{ guaranteeInfo.review_time }}
      .tip-text.mt2.f4 驳回理由：{{ guaranteeInfo.review_reason }}
      .flex.justify-center 
        |
        el-button.mt2(
          type="primary",
          size="large",
          round,
          @click="onGuaranteeApply"
        ) 重新发起担保申请
  //- 分页
  TablePagination(
    v-if="totalList > 0",
    :totalList="totalList",
    :page="form.page",
    @handleCurrentChange="handleCurrentChange")
  el-dialog(
    v-model="guaranteeVisible",
    width="683",
    align-center,
    :show-close="false",
    :destroy-on-close="true",
    center
  )
    Guarantee(
      @template="onQueryTemplate",
      @cancel="guaranteeVisible = false",
      @confirm="onGuaranteeConfirm"
    )
</template>

<script setup>
import { ref, getCurrentInstance, onMounted } from "vue";
import order1 from "@/assets/common/order-1.png";
import order2 from "@/assets/common/order-2.png";
import order3 from "@/assets/common/order-3.png";
import order4 from "@/assets/common/order-4.png";
import order5 from "@/assets/common/order-5.png";
import EnterpriseCenterTitle from "@/components/EnterpriseCenterTitle.vue";
import NotCertifiedYet from "@/views/end/enterprise-center/components/NotCertifiedYet.vue";
import Guarantee from "@/views/end/easy-quota/components/Guarantee.vue";
import TablePagination from "@/components/TablePagination.vue";
import { useRouter } from "vue-router";
import { GuaranteeMoneyLog } from "@/api/common";
import { CompanyInfo } from "@/api/login";
import contractApi from "@/api/contract";
import { getUserInfo, removeUserInfo } from "@/service";
const router = useRouter();
const { proxy } = getCurrentInstance();

const isGuarantee = ref(false); // 是否担保
const guaranteeMoney = ref(); // 担保金额
const guaranteeVisible = ref(false);
const guaranteeInfo = ref({
  estimate_money: "",
  review_status_text: "",
  review_status: "",
  review_reason: "",
  review_time: "",
  submit_time: "",
  signer: "",
  sign_status: "",
  company_sign_time: "",
  guarantor_sign_time: "",
  platform_sign_time: "",
  fdd_auth: "",
});
const statusType = ref([
  { id: 1, type: "进行中" },
  { id: 2, type: "已延期" },
  { id: 3, type: "已还款" },
  { id: 4, type: "已撤销" },
]);
const titleList = ref([
  {
    name: "先易额度",
    value: "",
  },
  {
    name: "可用额度",
    value: "",
  },
]);
const formRef = ref();
const form = ref({
  id: "",
  order_no: "", //关联订单号
  start_expected_repay_time: "", //预计还款时间
  end_expected_repay_time: "", //截止预计还款时间
  start_repay_time: "", //开始实际还款时间
  end_repay_time: "", //截止实际还款时间
  status: "", //状态
  start_create_time: "", //开始创建时间
  end_create_time: "", //截止创建时间
  page: 1,
  page_size: 10,
});
const tableHeaderStyle = ref({
  backgroundColor: "#E5E6EB",
  color: "#000000",
  textAlign: "center",
});
const tableCellStyle = ref({
  textAlign: "center",
});
const tableData = ref([]);
const tabs = ref([
  { name: "企业签订合同", active: false, time: "" },
  { name: "担保公司签订合同", active: false, time: "" },
  { name: "易可易平台签订合同", active: false, time: "" },
]);

const type=ref("")
// 生命周期
onMounted(() => {
  getGuaranteeInfo();
  getCompanyInfo();
  getGuaranteeMoneyLog();
  const userInfo = getUserInfo();
  type.value = userInfo.company.type;
});

// 获取担保审核签署信息
const getGuaranteeInfo = () => {
  contractApi.guaranteeInfo().then((res) => {
    if (res.code == 2) {
      isGuarantee.value = true;
    } else {
      guaranteeInfo.value = res.data;
      tabs.value.forEach((item, index) => {
        if (index + 1 <= res.data.signer) {
          item.active = true;
        }
      });
      tabs.value[0].time = res.data.company_sign_time
        ? res.data.company_sign_time
        : "--";
      tabs.value[1].time = res.data.guarantor_sign_time
        ? res.data.guarantor_sign_time
        : "--";
      tabs.value[2].time = res.data.platform_sign_time
        ? res.data.platform_sign_time
        : "--";
    }
  });
};

// 查看公司信息是否有额度
const getCompanyInfo = () => {
  CompanyInfo().then((res) => {
    titleList.value[0].value = res.data.guarantee_money;
    titleList.value[1].value = res.data.available_money;
    guaranteeInfo.value.fdd_auth = res.data.fdd_auth;
  });
};

// 先易额度列表
const getGuaranteeMoneyLog = () => {
  GuaranteeMoneyLog(form.value)
    .then((res) => {
      if (res.code == 1) {
        tableData.value = res.data.data;
        totalList.value = res.data.total;
      }
    })
    .catch((err) => {});
};

// 担保申请
const onGuaranteeApply = () => {
  if (guaranteeInfo.value.fdd_auth == 0) {
    contractApi.guaranteeAuth().then((res) => {
      if (res.code == 1) {
        window.open(res.data.url);
      }
    });
  } else {
    guaranteeVisible.value = true;
  }
};

// 查看模版
const onQueryTemplate = () => {
  contractApi.guaranteeTemplate().then((res) => {
    if (res.code == 1) {
      window.open(res.data.url);
    }
  });
};

// 去担保
const onGuaranteeConfirm = (money) => {
  contractApi.guaranteeApply({ money }).then((res) => {
    if (res.code == 1) {
      guaranteeVisible.value = false;
      setTimeout(() => {
        getGuaranteeInfo();
      }, 1000);
    }
  });
};

// 去签合同
const onSignContract = () => {
  contractApi
    .guaranteeSign({
      money: guaranteeMoney.value
        ? guaranteeMoney.value
        : guaranteeInfo.value.estimate_money,
    })
    .then((res) => {
      if (res.code == 1) {
        window.open(res.data.url);
      }
    });
};

// 切换状态
const typeChange = (val) => {
  form.value.status = val;
};
// 预计还款时间
const expectedChangeTime = (val) => {
  form.value.start_expected_repay_time = val;
  form.value.end_expected_repay_time = val;
};
// 实际还款时间
const repayChangeTime = (val) => {
  form.value.start_repay_time = val;
  form.value.end_repay_time = val;
};
// 创建时间
const createChangeTime = (val) => {
  form.value.start_create_time = val;
  form.value.end_create_time = val;
};

// 状态颜色和文本
const initStatusColor = (status) => {
  return status == 1 ? "" : status == 2 ? "overdue" : "refund";
};
const initStatusText = (status) => {
  return status == 1
    ? "进行中"
    : status == 2
    ? "已延期"
    : status == 3
    ? "已还款"
    : "已撤销";
};

// 查询
const onQueryChange = () => {
  getGuaranteeMoneyLog();
  proxy.$message.success("已查询");
};
// 重置
const onQueryReset = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
  getGuaranteeMoneyLog();
};

// 查看订单
const onLook = (row) => {

    // type==1 线上 type==2 线下
  //   if (type.value == 1) {
  //   console.log("type", type);
  //   router.push({
  //     path: "/order-detail-online",
  //     query: {
  //       id: row.id,
  //       type: 1,
  //     },
  //   });
  // }
  // if (type.value == 2) {
  //   router.push({
  //     path: "/order-detail-offline",
  //     query: {
  //       id: row.id,
  //       type: 1,
  //     },
  //   });
  // }
console.log('row',row);
  if(row.type==1){
    router.push({
    path: "/order-detail-online",
    query: {
      id: row.order_id,
      type:1
    },
  });
  }
  if(row.type==2){
    router.push({
    path: "/order-detail-offline",
    query: {
      id: row.order_id,
      type:1
    },
  });
  }

};
// 去还款
const onRefund = (row) => {
  console.log("去还款");
  router.push({
    path: "/repayment",
    query: {
      id: row.order_id,
      money: row.repay_money,
      type: 3,
      return_url: "/easy-quota",
    },
  });
};
// 赎回钱
const onRansom = (row) => {
  console.log("赎回钱", row);
  router.push({
    path: "/ransom-money",
    query: {
      id: row.id,
      money: row.repay_money,
      type: 3,
    },
  });
};
//数据总条数
const totalList = ref(0);

//分页
const handleCurrentChange = (val) => {
  form.value.page = val;
  getGuaranteeMoneyLog();
};
</script>

<style lang="stylus" scoped>
.easy-quota {
  .container {
    height: calc(100vh - 204px);
  }

  .overdue {
    color: #E84026;
  }

  .refund {
    color: #2487E8;
    cursor: pointer;
  }

  .no-quota {
    margin-top: 200px;
    font-size: 24px;
    font-weight: bold;
  }

  .reject {
    margin: 16px 30px;
    padding: 16px;
    background: #F5F5F5;
    border-radius: 6px 6px 6px 6px;

    .tip-error {
      color: #E84026;
    }

    .tip-loading {
      color: #18BC9F;
    }

    .tip-color {
      color: rgba(0, 0, 0, 0.87);
    }
  }

  .no-contract {
    padding: 22px 26px;

    .title {
      margin-bottom: 22px;
      font-weight: bold;
      font-size: 20px;
    }

    .content {
      padding: 16px 12px;
      border: 1px solid #E6E6E6;

      .quota {
        margin-bottom: 16px;
        font-weight: bold;
        color: #18BC9F;
      }

      .status {
        padding: 16px;
        background: #F5F5F5;
      }

      .tip {
        color: #E84026;
      }

      .input-quota {
        margin: 16px 0px;
      }

      .w-input {
        width: 220px;
      }

      .tabs {
        .img {
          width: 236px;
          height: 54px;
        }

        .item {
          width: 236px;
          height: 54px;
          line-height: 54px;
          color: rgba(0, 0, 0, 0.6);
        }

        .time {
          width: 236px;
          height: 34px;
          line-height: 34px;
          color: rgba(0, 0, 0, 0.6);
        }

        .active {
          color: #ffffff;
        }
      }
    }

    .btn {
      margin-top: 16px;
    }
  }
}
</style>
